#include <REGX52.h>
#include "LCD1602.h"

void Delayxms(unsigned int xms)		//@12.000MHz
{
	unsigned char i, j;
	
	while(xms--)
	{
		i = 12;
		j = 169;
		do
		{
			while (--j);
		} while (--i);
	}
	
}


unsigned char MatrixKeynum()
{
	unsigned char keynum = 0;
	P1 = 0XFF;
	P1_3 = 0;
	if(P1_7 == 0){Delayxms(20); while(P1_7 ==0 ); Delayxms(20); keynum = 1;}
	if(P1_6 == 0){Delayxms(20); while(P1_6 ==0 ); Delayxms(20); keynum = 5;}
	if(P1_5 == 0){Delayxms(20); while(P1_5 ==0 ); Delayxms(20); keynum = 9;}
	if(P1_4 == 0){Delayxms(20); while(P1_4 ==0 ); Delayxms(20); keynum = 13;}
	
	P1 = 0XFF;
	P1_2 = 0;
	if(P1_7 == 0){Delayxms(20); while(P1_7 ==0 ); Delayxms(20); keynum = 2;}
	if(P1_6 == 0){Delayxms(20); while(P1_6 ==0 ); Delayxms(20); keynum = 6;}
	if(P1_5 == 0){Delayxms(20); while(P1_5 ==0 ); Delayxms(20); keynum = 10;}
	if(P1_4 == 0){Delayxms(20); while(P1_4 ==0 ); Delayxms(20); keynum = 14;}
	
	P1 = 0XFF;
	P1_1 = 0;
	if(P1_7 == 0){Delayxms(20); while(P1_7 ==0 ); Delayxms(20); keynum = 3;}
	if(P1_6 == 0){Delayxms(20); while(P1_6 ==0 ); Delayxms(20); keynum = 7;}
	if(P1_5 == 0){Delayxms(20); while(P1_5 ==0 ); Delayxms(20); keynum = 11;}
	if(P1_4 == 0){Delayxms(20); while(P1_4 ==0 ); Delayxms(20); keynum = 15;}
	
	P1 = 0XFF;
	P1_0 = 0;
	if(P1_7 == 0){Delayxms(20); while(P1_7 ==0 ); Delayxms(20); keynum = 4;}
	if(P1_6 == 0){Delayxms(20); while(P1_6 ==0 ); Delayxms(20); keynum = 8;}
	if(P1_5 == 0){Delayxms(20); while(P1_5 ==0 ); Delayxms(20); keynum = 12;}
	if(P1_4 == 0){Delayxms(20); while(P1_4 ==0 ); Delayxms(20); keynum = 16;}
	
	return keynum;
}

void main()
{
	unsigned char keynum = 0;
	
	LCD_Init();
	LCD_ShowString(1, 1, "MatrixKey");
	
	while(1)
	{
		keynum = MatrixKeynum();
		LCD_ShowNum(2, 1, keynum, 2);
	}
	

}
